package com.cx.bank.util;

import com.cx.bank.pojo.Log;
import com.cx.bank.pojo.User;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jxau_scf
 * @date 2021/7/25 - 10:41
 */
public class LogUtil {
    private LogUtil(){

    }

    public static void insertLog(Log log){
        Connection conn = DBHelper.getConn();
        String sql = "insert into t_log(log_type,log_amount,user_id) values(?,?,?)";
        List<Object> logList = new ArrayList<>();
        logList.add(log.getLogType());
        logList.add(log.getLogAmount());
        logList.add(log.getUserId());
        boolean insertLogStatus = DBHelper.updateDate(conn, sql, logList);
        if (insertLogStatus) {
            System.out.println(log.getUserId()+"号用户，日志添加成功！");
            System.out.println(log);
        }
    }

    public static List<Log> queryLogByUserId(Integer userId) throws SQLException {
        Connection conn = DBHelper.getConn();
        String sql = "select * from t_log where user_id = ?";
        List<Object> userIdList = new ArrayList<>();
        userIdList.add(userId);
        ResultSet resultSet = DBHelper.queryDate(conn, sql, userIdList);
        List<Log> userLogList = new ArrayList<>();
//        Log log = new Log();
        while (resultSet.next()) {
            int logId = resultSet.getInt("log_id");
            String logType = resultSet.getString("log_type");
            double logAmount = resultSet.getDouble("log_amount");
//            new Log(logId,logType,logAmount,userId)
//            log.setLogId(logId);
//            log.setLogType(logType);
//            log.setLogAmount(logAmount);
//            log.setUserId(userId);
            userLogList.add(new Log(logId,logType,logAmount,userId));
        }
        return userLogList;
    }

    public static int findUserIdByUserName(String userName) throws SQLException {
        Connection conn = DBHelper.getConn();
        String sql = "select user_id from t_user where user_name = ?";
        List<Object> userNameList = new ArrayList<>();
        userNameList.add(userName);
        ResultSet resultSet = DBHelper.queryDate(conn, sql, userNameList);
        int userIdInDB = 0;
        while (resultSet.next()){
            userIdInDB = resultSet.getInt("user_id");
        }
        return userIdInDB;
    }
}
